import screepsapi
import time
import datetime

TOKEN = "6a49ab20-1cf4-4b11-afe4-e7f8541529f6"
api = screepsapi.API(token=TOKEN)
temp = ''


def print_nuke_new(shard_name):
    print("获取{}时间".format(shard_name))
    game_time = api.time(shard_name)
    time.sleep(3)
    print(game_time)
    print("获取核弹数据")
    nuker = api.nukes()
    time.sleep(3)
    # print(nuker2)
    # print(nuker2['nukes'])
    nukers = nuker['nukes']
    # print(nukers[shard_name])
    s0nukers = nukers[shard_name]
    # print(s0nukers[1]['room'])
    global temp
    temp += "======================" + shard_name + "======================" + "\n"
    print(shard_name)
    for mix in s0nukers:
        time.sleep(3)
        try:
            launchRoomName = api.room_overview(mix['launchRoomName'], shard=shard_name)['owner']['username']
        except:
            launchRoomName = "?"
        time.sleep(3)
        try:
            room = api.room_overview(mix['room'], shard=shard_name)['owner']['username']
        except:
            room = "?"
        time.sleep(3)
        result = (mix['launchRoomName'] + " [ " + launchRoomName + " ] " + "=> " +
                  mix['room'] + " [ " + room + " ] " + ": " +
                  str(mix['landTime'] - game_time))
        print(result)
        temp += result + '\n'
    print(temp)


def save(temp):
    # 要写入的新字符串
    new_text = temp
    # 使用'w'模式打开文件，如果文件已存在则清空内容
    # 使用服务器的脚本进行拷贝结果
    with open('nukerList.txt', 'w', encoding='utf-8') as file:
        # 写入新字符串
        file.write(new_text)


def getShardNuker():
    print("开始获取数据")
    print_nuke_new('shard0')
    time.sleep(3)
    print_nuke_new('shard1')
    time.sleep(3)
    print_nuke_new('shard2')
    time.sleep(3)
    print_nuke_new('shard3')
    time.sleep(3)


def runmain():
    global temp
    temp = ''
    print('核弹监控启动')
    start_time = time.time()
    user = api.me()
    time.sleep(3)
    print("使用", user['username'], "的Key进行爬取")
    game_time_now = api.time('shard3')
    time.sleep(3)
    print("当前S3游戏时间为", game_time_now)
    getShardNuker()
    end_time = time.time()
    print("本轮此请求请求耗时: {:.2f}秒".format(end_time - start_time))
    temp += "$$$takes {:.2f} seconds$$$\n".format(end_time - start_time)
    current_time = datetime.datetime.now()
    print(current_time)
    temp += "$$$" + str(current_time) + "$$$"
    print(temp)
    save(temp)
    time.sleep(1200)

def go():
    while True:
        try:
            runmain()
        except:
            print("crush")


if __name__ == '__main__':
    try:
        runmain()
    except:
        print("crush")
